/*
 * string.c
 *
 *  Created on: 2020��10��12��
 *      Author: Administrator
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "../../include/common.h"
#include "../../include/string/string.h"

void init_string(SString* s) {

	s->len = 0;
}

SString* create_string(char array[], int length) {

	SString* s = (SString *)malloc(sizeof(SString));
	init_string(s);

	for (int i = 0; i < length; ++i) {
		s->ch[i] = array[i];
		s->len++;
	}

	return s;
}

int is_empty_string(SString* s) {

	if (s->len == 0) {
		return true;
	}
	return false;
}

int is_full_string(SString* s) {

	if (s->len == MAXLEN) return true;
	return false;
}

int insert_string(SString* s, int pos, SString* t) {

	if (pos < 0 || pos > s->len) return ERROR;
	if (is_full_string(s)) return false;
	// �������ַ����󳬹���������
	if (s->len + t->len > MAXLEN) {
		printf("���鳤�Ȳ���!\n");
		return false;
	} else { // �������ַ���û�г�������
		// Ԫ�غ���
		for (int i = s->len + t->len - 1; i >= pos + t->len; i--) {
			s->ch[i] = s->ch[i - t->len];
		}
		// �ַ�������
		for (int j = 0; j < t->len; j++) {
			s->ch[j+pos] = t->ch[j];
		}
		s->len += t->len;
	}
	return true;
}

int delete_string(SString* s, int pos, int len) {

	if (pos < 0 || pos > s->len) return ERROR;
	if (is_empty_string(s)) return false;

	for (int i = pos + len; i < s->len; ++i) {
		s->ch[i-len] = s->ch[i];
	}
	s->len -= len;
	return true;
}

void copy_string(SString* s, SString* t) {

	for (int i = 0; i < t->len; ++i) {
		s->ch[i] = t->ch[i];
		s->len++;
	}
}

int compare_string(SString* s, SString* t) {

	for (int i = 0; i < s->len; ++i) {
		if (s->ch[i] != t->ch[i]) {
			return s->ch[i] - t->ch[i];
		}
	}
	return s->len - t->len;
}

int concat_string(SString* s, SString* t) {

	if (s->len + t->len > MAXLEN) {
		printf("space of s string is not enough!\n");
		return ERROR;
	} else {
		// 将t字符串复制到s字符串
		for (int i = s->len; i < s->len + t->len; ++i) {
			s->ch[i] = t->ch[i - s->len];
		}
		s->len += t->len;
		return true;
	}
}

int sub_string(SString* s, SString* sub, int pos, int len) {

	if (pos < 0 || pos > s->len) return ERROR;
	if (len < 1 || len > s->len - pos) return ERROR;

	for (int i = 0; i < len; ++i) {
		sub->ch[i] = s->ch[i + pos];
		sub->len++;
	}
	return true;
}

int index_string(SString* s, int pos, SString* pattern) {

	int start = pos;
	int i = start;  // 主串从pos开始
	int j = 0;      // 模式串从0开始
	if (pattern->len == 0) return 0;
	while (i < s->len && j < pattern->len) {
		if (s->ch[i] == pattern->ch[j]) {
			i++;
			j++;
		} else {
			start++;
			i = start;
			j = 0;
		}
	}
	// 匹配成功
	if (j == pattern->len) {
		return start;
	} else {
		return -1;
	}
}

void print_string(SString* s) {

	for (int i = 0; i < s->len; ++i) {
		printf("%c", s->ch[i]);
	}
	printf("\n");
}
